package com.mazihao.emos.db.dao;

import com.mazihao.emos.db.pojo.MessageRefEntity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MessageRefDao {

    @Autowired
    @Qualifier("mongoTemplate")
    private MongoTemplate mongoTemplate;

    /**
     * 新增消息接收类消息进mongoDB
     * @param messageRefEntity
     * @return
     */
    public String insert(MessageRefEntity messageRefEntity) {
        messageRefEntity = mongoTemplate.save(messageRefEntity);
        return messageRefEntity.get_id();
    }

    /**
     * 查询未读信息数量
     * @param userId
     * @return
     */
    public long searchUnreadCount(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("readFlag").is(false).and("receiverId").is(userId));
        return mongoTemplate.count(query, MessageRefEntity.class);
    }

    /**
     * 查询最新消息数量（每次轮询到的数据为最新消息）
     * @param userId
     * @return
     */
    public long searchLastCount(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("lastFlag").is(true).and("receiverId").is(userId));
        Update update = new Update();
        update.set("lastFlag", false);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, "message_ref");
        return updateResult.getModifiedCount();
    }

    /**
     * 更新未读消息
     * @param id
     * @return
     */
    public long updateUnreadMessage(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("readFlag", true);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "message_ref");
        return updateResult.getModifiedCount();
    }

    /**
     * 根据id删除消息接收类数据
     * @param id
     * @return
     */
    public long deleteMessageRefById(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, "message_ref");
        return deleteResult.getDeletedCount();
    }

    /**
     * 删除用户消息类
     * @param userId
     * @return
     */
    public long deleteUserMessageRef(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("receiverId").is(userId));
        DeleteResult deleteResult = mongoTemplate.remove(query, "message_ref");
        return deleteResult.getDeletedCount();
    }
}
